package com.lej.core.base

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.multidex.MultiDex
import com.lej.core.BuildConfig
import com.lej.core.daq.DAQEvent
import com.lej.core.utils.KLog
import java.util.*

open class BaseApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        mInstance = this
        //是否开启打印日志
        KLog.init(isDebug)
        setApplication(this)
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    open fun privacyInit() {}

    /**
     * 判断是否是debug模式
     */
    open val isDebug = BuildConfig.DEBUG

    companion object {
        //每次应用启动时候生成的唯一标识,作为埋点使用
        val sessionId: String = UUID.randomUUID().toString()
        val shortSessionId = sessionId.takeLast(8)
        private lateinit var mInstance: BaseApplication

        /**
         * 当主工程没有继承BaseApplication时，可以使用setApplication方法初始化BaseApplication
         */
        fun setApplication(application: Application) {
            //注册监听每个activity的生命周期,便于堆栈式管理
            application.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
                override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                    AppManager.addActivity(activity)
                    DAQEvent.activity_create.eventPage(activity)
                }

                override fun onActivityStarted(activity: Activity) {
                    DAQEvent.activity_start.eventPage(activity)
                }

                override fun onActivityResumed(activity: Activity) {
                }

                override fun onActivityPaused(activity: Activity) {
                }

                override fun onActivityStopped(activity: Activity) {
                    DAQEvent.activity_stop.eventPage(activity)
                }

                override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
                }

                override fun onActivityDestroyed(activity: Activity) {
                    AppManager.removeActivity(activity)
                    DAQEvent.activity_destroy.eventPage(activity)
                }
            })
        }

        /**
         * 获得当前app运行的Application
         */
        val instance: BaseApplication get() = mInstance

        val initList: MutableList<BaseAppInit> = ArrayList()
    }
}